﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Extensions;
using UnityGameFramework.Runtime;

namespace StarForce {
    public class PlayerHandBender : MonoBehaviour {
        [SerializeField] private UiCardParameters parameters;
        [SerializeField] [Tooltip("用来定位卡牌的点")] private Transform pivot;
        /// <summary>
        /// 每张卡牌的宽度
        /// </summary>
        private float CardWidth = 6;

        private float CardSpacing = 0;

        private PlayerHand m_PlayerHand;

        private void Awake() {
            m_PlayerHand = GetComponent<PlayerHand>();
            m_PlayerHand.OnPileChange += Bend;
        }

        public void Bend(Card[] cards) {
            if (cards == null) {
                throw new ArgumentNullException("Card List can not be empty！");
            }

            CardSpacing = parameters.Spacing;
            float fullAngle = -parameters.BentAngle;    // 总角度
            float anglePerCard = fullAngle / cards.Length;    // 每张卡牌的角度
            float firstAngle = CalcFirstAngle(fullAngle);    // 第一张卡牌的角度
            float handWidth = ChangeCardSpacing(cards.Length);    // 手牌宽度
            //ChangeCardSpacing(cards.Length);
            //Debug.LogError("卡牌宽度："+handWidth);

            int pivotLocationFactor = pivot.CloserEdge(Camera.main, Screen.width, Screen.height);
            // 计算出第一张牌距离锚点的x轴偏移
            float offsetX = pivot.position.x - handWidth / 2;
            
            // 排列
            for (int i = 0; i < cards.Length; i++) {
                var card = cards[i];
                // 计算z轴旋转
                float angleTwist = (firstAngle + i * anglePerCard) * pivotLocationFactor;
                // 计算x轴位置
                float xPos = offsetX + CardWidth / 2;
                // 计算y轴位置
                var yDistance = Mathf.Abs(angleTwist) * parameters.Height;
                var yPos = pivot.position.y - yDistance * pivotLocationFactor;
                
                // 设置卡牌位置
                var zAxisRot = pivotLocationFactor == 1 ? 0 : 180;
                var rotation = new Vector3(0, 0, angleTwist - zAxisRot);
                var position = new Vector3(xPos, yPos, 0);

                var rotSpeed = parameters.RotationSpeed;
                card.MoveTo(position,parameters.MovementSpeed);
                card.RotateTo(rotation, rotSpeed);
                offsetX += (CardWidth + CardSpacing);
            }
        }

        /// <summary>
        /// 计算第一张卡的角度（魔法）
        /// </summary>
        /// <param name="fullAngle"></param>
        /// <returns></returns>
        private float CalcFirstAngle(float fullAngle) {
            float magicMathFactor = 0.1f;
            return -(fullAngle / 2) + fullAngle * magicMathFactor;
        }
        /// <summary>
        /// 计算玩家手牌的宽度
        /// </summary>
        /// <param name="quantityOfCards"></param>
        /// <returns></returns>
        private float CalcHandWidth(int quantityOfCards,float spacing) {
            float widthCards = quantityOfCards * CardWidth;
            float widthSpacing = (quantityOfCards - 1) * spacing;
            return widthCards + widthSpacing;
        }

        private float ChangeCardSpacing(int quantityOfCards) {
            float cameraHeight = Camera.main.orthographicSize * 2;
            float cameraWidth = Camera.main.aspect * cameraHeight;
            float handWidth =  CalcHandWidth(quantityOfCards,CardSpacing);
            cameraWidth = cameraWidth - 5;
            if (handWidth > cameraWidth) {
                float judge = handWidth - cameraWidth;
                while (judge > 0) {
                    CardSpacing -= 0.05f;
                    handWidth =  CalcHandWidth(quantityOfCards,CardSpacing);
                    judge = handWidth - cameraWidth;
                }
            }
            return handWidth;
        }
    }
}
